package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.PersonnelAdapter;
import com.ljkj.cordial.chat.base.BaseActivity;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.EmptyMessageEvent;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.widget.RectButtonHintDialog;
import com.nic.view.model.CheckType;
import com.nic.view.util.contactList.PinyinListView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 消息转发好友
 */
public class TransmitFriendActivity extends BaseActivity implements PersonnelAdapter.OnItemClickListener {

    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.listView)
    PinyinListView listView;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_go)
    TextView tvGo;
    private PersonnelAdapter personnelAdapter;
    private FriendTable friendTable;
    private EmptyMessageEvent info;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_transmit_friend;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbar().setTitle("转发好友");
        info = (EmptyMessageEvent) getIntent().getSerializableExtra(Canstants.KEY_INFO);
        personnelAdapter = new PersonnelAdapter(CheckType.NONE);
        personnelAdapter.setOnItemClickListener(this);
        listView.getListView().setAdapter(personnelAdapter);
        listView.setBarSelectionListener(new PinyinListView.onSideBarSelectionListener() {
            @Override
            public void onSelected(String selectStr) {
                for (int i = 0; i < personnelAdapter.getList().size(); i++) {
                    FriendTable bean = personnelAdapter.getList().get(i);
                    if (bean.getFirstLetter().equals(selectStr) && TextUtils.isEmpty(bean.getPinyin())) {
                        listView.getListView().setSelection(i);
                    }
                }
            }
        });
        listView.getListView().setEmptyView(ivEmpty);
        queryOfflineData();
    }

    public void setData(List<FriendTable> userInfors) {
        PinyinListView.insertTitle(userInfors, new PinyinListView.PinyinFactory<FriendTable>() {

            @Override
            public FriendTable create() {
                return new FriendTable();
            }

            @Override
            public void finish(final List<FriendTable> t) {
                if (!isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            personnelAdapter.setList(t);
                        }
                    });
                }


            }
        });
    }

    public void queryOfflineData() {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<List<FriendTable>>() {
            @Override
            public void onAction(List<FriendTable> list) {
                search(list);
            }

            @Override
            public List<FriendTable> onThreadAction() {
                return FriendTable.queryNoCurrentUser();
            }
        });

    }

    private void search(List<FriendTable> list) {
        if (list != null && !list.isEmpty()) {
            setData(list);
        } else {
            personnelAdapter.clear();
        }
    }

    public static void jumpTo(Activity activity, EmptyMessageEvent msg) {
        Intent intent = new Intent(activity, TransmitFriendActivity.class);
        intent.putExtra(Canstants.KEY_INFO, msg);
        activity.startActivityForResult(intent, Canstants.REQUEST_CODE_BACK);
    }

    @OnClick({R.id.tv_back, R.id.tv_go})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_go:
                if (friendTable != null) {
                    setResult(Canstants.REQUEST_CODE_BACK);
                    finish();
                    GroupChatActivity.jumpTo(this, Canstants.SINGLE_CHAT,
                            friendTable.getFriendNickname(), friendTable.getFriendUserId(), friendTable.getUserType());
                }

                break;
        }
    }

    private void doSend(String friendNickname, String friendUserId, String userType) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatTableBean>() {
            @Override
            public void onAction(ChatTableBean obj) {
                if (!isFinishing() && obj != null) {
                    setResult(Canstants.REQUEST_CODE_BACK);
                    finish();
                    GroupChatActivity.jumpTo(mContext, Canstants.SINGLE_CHAT,
                            friendNickname, friendUserId, userType);
                }
            }

            @Override
            public ChatTableBean onThreadAction() {
                ChatTableBean chat = ChatTableBean.getTableFromId(info.getMsgId());
                if (chat != null) {
                    setLoginUserAndInsertChat(chat, friendTable);
//                    if (!ChatContentTable.isExistTableByTargetId(friendUserId)) {
                    ChatContentTable chatTableBean = ChatContentTable.queryRowByTargetIdNotNull(friendTable.getFriendUserId(), Canstants.SINGLE_CHAT);
                    chatTableBean.setChatType(Canstants.SINGLE_CHAT);
                    chatTableBean.setTargetId(friendTable.getFriendUserId());
                    chatTableBean.setTargetName(friendTable.getFriendNickname());
                    chatTableBean.setTargetType(friendTable.getUserType());
                    chatTableBean.setTargetAvatarUrl(friendTable.getFriendAvatar());
                    chatTableBean.setLastMsgType(chat.getChatType());
                    chatTableBean.setLastMsg(chat.getTextMsg());
                    chatTableBean.setIsRead(0);
                    chatTableBean.setIsTOP(0);
                    chatTableBean.setUpdateTime(System.currentTimeMillis());
                    ChatContentTable.insert(chatTableBean);
//                    }
                }
                return chat;
            }
        });
    }

    private void setLoginUserAndInsertChat(ChatTableBean msg, FriendTable t) {
        UserTableBean u = UserTableBean.getCurrentUser();
        if (u != null) {
            msg.setChatAvatarUrl(u.getAvatar());
            msg.setTargetName(u.getNickname());
            if (TextUtils.isEmpty(u.getUserId())) {
                msg.setTargetId(u.getTemporaryId());
            } else {
                msg.setTargetId(u.getUserId());
            }

            msg.setTargetType(u.getUserType());
            msg.setSendState(ChatTableBean.SEND_ING);
            msg.setChatUnRead(ChatTableBean.UNREAD);
            msg.setSendType(ChatTableBean.SEND);
            msg.setChatName(t.getFriendUserId());
            msg.setGroupId(null);
            msg.setGroupType(null);
            msg.setMsgTime(System.currentTimeMillis());
            msg.setHistoryTime(System.currentTimeMillis());
            ChatTableBean.insert(msg);
        }
    }

    @Override
    public void onItemClick(View view, Object obj, int position) {
        friendTable = (FriendTable) obj;
        if (friendTable == null) {
            return;
        }
        new RectButtonHintDialog(this)
                .setTitle("发送给：" + friendTable.getFriendNickname())
                .setLeftSubmit("取消", v -> {
                    finish();
                })
                .setRightSubmit("发送", v -> doSend(friendTable.getFriendNickname(), friendTable.getFriendUserId(), friendTable.getUserType()))
                .show();
    }
}
